<!-- 地图编辑功能 -->
<template>
  <div class="map-content">
    <template>
      <div class="color">
        <div class="size"><span>作业范围分配</span></div>
        <div
          v-if="isShow"
          class="button"
        >
          <el-button
            v-if="change"
            style="width: 86px; height: 40px"
            type="danger"
            @click="changeButton"
          >编辑</el-button>
          <el-button
            v-if="cancel"
            style="width: 86px; height: 40px"
            type="danger"
            @click="save"
          >保存</el-button>
          <el-button
            v-if="cancel"
            style="width: 86px; height: 40px"
            @click="cancelButton"
          >取消</el-button>
        </div>
      </div>
    </template>
    <template>
      <div class="color2">
        <div class="input">
          地区关键词:
          <el-input
            v-model="inputText"
            placeholder="请输入地区关键词"
            style="width:200px"
            @blur="blur"
          ></el-input>
        </div>
        <div
          v-if="div"
          class="go"
        >
          <el-button
            v-if="Begin"
            type="danger"
            style="width:98px ; height: 40px"
            @click="startButton"
          >
            开始绘制</el-button>
          <el-button
            v-if="fencing"
            type="danger"
            style="width:98px ; height: 40px"
            @click="finishButton"
          >
            完成绘制</el-button>
          <el-button
            v-if="fencing"
            style="width:98px ; height: 40px"
            @click="deleteButton"
          >
            删除围栏</el-button>
          <el-alert
            title="点击或拖动鼠标绘制电子围栏，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。仅支持绘制单个电子围栏区域"
            type="warning"
            show-icon
            style="margin-top: 20px"
            size="mini"
            :closable="false"
          >
          </el-alert>
        </div>
        <div
          ref="map"
          class="map"
        ></div>
      </div>
    </template>
  </div>
</template>

<script>
import { courierScopeList, courierAdd, deleteCourierScope } from '@/api/branch'
export default {
  props: {
    id: {
      type: String,
      default: '1024985129287809409'
    },
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputText: '',
      map: '',
      change: true,
      cancel: false,
      Begin: true,
      fencing: false,
      polygon: '',
      div: false,
      formData: {
        bid: '',
        created: '',
        latitude: '',
        longitude: '',
        polygon: [],
        type: '',
        updated: ''
      },
      type: 1,
      latitude: '',
      longitude: '',
      polygons: [],
      isAB: false,
      redact: []
    }
  },
  watch: {
    async id(nv) {
      // id一变化拉取数据
      this.getData()
    }
  },
  async mounted() {
    // 拉取数据
    this.getData()
  },
  methods: {
    // 刷新数据
    refresh() {
      this.$nextTick(async () => {
        const res = await courierAdd(this.formData)
        if (res.code === 200) {
          this.$message.success('保存成功')
          // 从新拉去数据
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
        this.cancel = false
        this.change = true
        this.div = false
        // this.polygon.disableEditing()
      })
    },
    async getData() {
      const id = this.id
      const { data } = await courierScopeList(id, 1)
      this.latitude = data.latitude
      this.longitude = data.longitude
      this.polygons = data.polygon
      this.formData = data
      this.map = new BMap.Map(this.$refs.map)
      // 创建地图实例
      var point = new BMap.Point(this.longitude, this.latitude)
      // 创建点坐标
      this.map.centerAndZoom(point, 12)
      // 初始化地图，设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
      this.mapPlygon()
    },
    // 地图折线
    async mapPlygon() {
      if (this.polygons) {
        // 有数据就便利
        const arr = []
        this.polygons.forEach(item => {
          arr.push(new BMap.Point(item.longitude, item.latitude))
        })
        this.polygon = new BMap.Polygon(arr, {
          strokeColor: 'red',
          fillColor: '#f9c39e',
          strokeStyle: 'dashed',
          strokeWeight: 2,
          strokeOpacity: 0.5
        })
        this.map.addOverlay(this.polygon) // 创建折线)
      }
    },
    // 按钮的取消隐藏 /// 编辑按钮
    changeButton() {
      this.change = false
      this.cancel = true
      this.div = true
    },
    // 取消按钮
    cancelButton() {
      this.cancel = false
      this.change = true
      this.div = false
      this.fencing = false
      this.Begin = true
      // 重新拉取数据
      this.getData()
    },
    // 保存 -- 提交数据
    async save() {
      if (this.isAB) {
        const polygon = []
        const arr = await this.redact
        arr.push(arr[0])
        await arr.forEach(item => {
          polygon.push({
            latitude: item.lat,
            longitude: item.lng
          })
        })
        this.formData.polygon = polygon
        this.formData.bid = this.id
        this.formData.type = 1
        // 刷新数据
        this.refresh()
        this.finishButton()
        this.isAB = false
      } else {
        const polygon = []
        const arr = await this.polygon.getPath()
        await arr.forEach((item, index) => {
          polygon.push({
            latitude: item.lat,
            longitude: item.lng
          })
        })
        this.formData.polygon = polygon
        // 刷新数据
        this.refresh()
        this.finishButton()
        this.isAB = false
      }
    },
    // 开始绘制按钮
    startButton() {
      this.Begin = false
      this.fencing = true
      if (!this.polygons) {
        this.isAB = true
        this.clickDraw()
      } else {

      }
      this.polygon.enableEditing()
    },
    // 完成绘制
    finishButton() {
      this.fencing = false
      this.Begin = true
      // this.polygon.disableEditing()
    },
    // 删除围栏
    async deleteButton() {
      this.fencing = false
      this.Begin = true
      // ------------------------------------------
      this.$nextTick(async () => {
        const res = await deleteCourierScope(this.id, 1)
        if (res.code === 200) {
          this.$message.success('保存成功')
          // 从新拉去数据
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
        this.cancel = false
        this.change = true
        this.div = false
        // this.polygon.disableEditing()
      })
      this.finishButton()
      this.isAB = false
      // 从新拉去数据
      this.getData()
    },
    // 搜索框失去焦点触发
    blur() {
      const myGeo = new BMap.Geocoder()
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(
        this.inputText,
        point => {
          if (point) {
            this.map.centerAndZoom(point, 10)
            this.map.addOverlay(new BMap.Marker(point))
          }
        },
        this.inputText
      )
    },
    // 点击画图
    clickDraw() {
      this.map.centerAndZoom(new BMap.Point(this.longitude, this.latitude), 12)
      var p = [] // 用来存储折线的点

      var polygon
      var doneDraw = true // 判断是否绘制折线结束
      this.map.addEventListener('click', (e1) => {
        // 当鼠标单击时
        if (doneDraw) {
          // 判断是否绘制曲线完毕
          p.push(new BMap.Point(e1.point.lng, e1.point.lat)) // 存储曲线上每个点的经纬度
          if (polygon) {
            polygon.setPath(p)
            this.redact = polygon.getPath(p)

            // 如果曲线存在，则获取折线上的点
          } else {
            polygon = new BMap.Polygon(p, {
              strokeColor: 'red',
              fillColor: '#f9c39e',
              strokeStyle: 'dashed',
              strokeWeight: 2,
              strokeOpacity: 0.5
            })
          } // 如果折线不存在，就增加此点
          if (p.length < 2) {
            return
          } // 当折线上的点只有一个时，不绘制
          this.map.addOverlay(polygon) // 绘制曲线
        }
      })
      // this.map.addEventListener('dblclick', function(e2) {
      //   // 当鼠标双击时：结束绘制，并可以编辑曲线
      //   // alert('绘制完成')
      //   doneDraw = false
      //   // polygon.enableEditing()
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.color {
  background-color: #f8faff;
  height: 60px;
  margin: 30px 20px 0 20px;
  // padding: 10px 10px 0;
  display: flex;
  justify-content: space-between;
}
.color2 {
  background-color: #ffffff;
  height: 800px;
  margin: 0 20px;
  display: flex;
  flex-direction: column;
}
.size {
  font-size: 16px;
  font-weight: bold;
  height: 100%;
  padding: 20px;
}
.button {
  padding: 10px;
  float: right;
}
.input {
  padding: 20px 0 60px 25px;
  width: 100%;
  height: 40px;
}
.map {
  // flex: 1;
  height: 100%;
  width: 100%;
}
.go {
  position: relative;
  top: -2%;
  z-index: 99;
  height: 100px;
  width: 87%;
  padding-left: 20px;
  margin-right: 20px;
  background-color: #ffffff;
}
</style>
